package com.ajl.wx.module.websocket;

import com.ajl.wx.config.SpringContext;
import com.ajl.wx.module.wechat.service.impl.TbWechatUserServiceImpl;
import com.ajl.wx.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * WebSocket监听管理
 */
@ServerEndpoint("/chat/{id}")
@Component
public class WebSocketListener {
    private Logger logger = LoggerFactory.getLogger(WebSocketListener.class);
    static WebSocketManager webSocketManager=WebSocketManager.getInstance();

    public WebSocketListener() {
        logger.info("WebSocketListener init");
    }

    /**
     * 客户端连接
     *
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String userId) throws IOException {
        if (StringUtils.isNull(userId)) {
            session.close();
            return;
        }
        webSocketManager.addUser(userId, session);
    }

    /**
     * 客户端关闭
     *
     * @param userId
     */
    @OnClose
    public void onClose(@PathParam(value = "id") String userId) {
        webSocketManager.remove(userId);
    }

    /**
     * 消息到来
     * @param userId
     * @param messag
     */
    @OnMessage
    public void onMessage(@PathParam(value = "id") String userId,String messag){
        logger.info("onMessage{},{}",userId,messag);
        TbWechatUserServiceImpl wechatUserService = SpringContext.getBean(TbWechatUserServiceImpl.class);
        webSocketManager.broadcastMessage(wechatUserService.getById(userId),messag);

    }

}
